package com.service;

import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import com.service.IMailService;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class MailServiceImpl implements IMailService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String from;


    @Override
    public void sendMail(String mail) {

        //产生验证码，并保存到redis
        String code = RandomUtil.randomString(4);
        redisTemplate.boundValueOps(mail).set(code);
        redisTemplate.boundValueOps(mail).expire(30, TimeUnit.MINUTES);

        //发送
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(mail);
        message.setSubject("验证码注册");
        javaMailSender.send(message);
    }
    @Override
    public boolean checkCode(String mail, String code) {
        //从redis取出验证码
            String redisCode=(String) redisTemplate.boundValueOps(mail).get();
            //判断验证码是否正常
        boolean f=(code!=null && code.equalsIgnoreCase(redisCode));
        if (f){
            //成功之后删除原来
            redisTemplate.boundValueOps(mail).expire(0,TimeUnit.MILLISECONDS);
        }
            return f;


    }
}
